package com.abocode.aichat.core.domain.repository;

import com.abocode.aichat.core.domain.entity.Message;
import com.abocode.aichat.core.interfaces.constant.ApplicationConstant;
import com.abocode.aichat.data.Entity;
import com.abocode.aichat.data.EntityImpl;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

/**
 * @author guanxf
 */
@Repository
public class RedisMessageRepository {
    @Autowired
    private RedisTemplate redisTemplate;
    private final static String prefix = "chat:message:";
    public void save(Message message) {
        String jid = String.valueOf(message.getTo());
        Entity entity = EntityImpl.parse(jid);
        final String value=JSON.toJSONString(message);
        final String offlineKey = prefix + entity.getNode();
        if(ApplicationConstant.MESSAGE_IS_OFFLINE=="offline"){
            //保存离线
            redisTemplate.execute(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection)
                        throws DataAccessException {
                    connection.set(
                            redisTemplate.getStringSerializer().serialize(offlineKey),
                            redisTemplate.getStringSerializer().serialize(value));
                    return null;
                }
            });
        }
    }

    public Object get(final String msgKey) {
        return redisTemplate.execute(new RedisCallback<Object>() {

            @Override
            public Object doInRedis(RedisConnection connection)
                    throws DataAccessException {
                byte[] key = redisTemplate.getStringSerializer().serialize(msgKey);
                if (connection.exists(key)) {
                    byte[] value = connection.get(key);
                    Object object = redisTemplate.getStringSerializer().deserialize(value);
                    return object;
                }
                return null;
            }
        });
    }
}
